package com.codeplex.jtfscli.util;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class TextTable {
	private List<String[]> rows = new LinkedList<String[]>();

	public TextTable(final String... header) {
		this.rows.add(header);
	}

	/**
	 * Adds a row to this text table. The row added must have the same number of
	 * columns as all other rows in the table. Otherwise, this method will throw
	 * an {@link IllegalArgumentException}.
	 * 
	 * @param row
	 */
	public void add(final String... row) {
		if (row.length != rows.get(0).length)
			throw new IllegalArgumentException(
					"The number of columns in this row must be exactly "
							+ rows.get(0).length + ". Instead, it was "
							+ row.length + ".");
		this.rows.add(row);
	}

	public static int[] computeColumnWidths(final List<String[]> rows) {
		int[] widths = new int[rows.get(0).length];
		for (int i = 0; i < widths.length; i++)
			widths[i] = 0;
		for (final String[] row : rows) {
			for (int i = 0; i < row.length; i++)
				widths[i] = Math.max(widths[i], row[i].length());
		}
		return widths;
	}

	public String toString() {
		final StringBuilder sb = new StringBuilder();
		final int[] widths = computeColumnWidths(this.rows);
		final Iterator<String[]> itr = rows.iterator();
		final String[] header = itr.next();
		for (int i = 0; i < header.length; i++) {
			sb.append(StringUtils.rightPad(header[i], widths[i], ' ')).append(
					" ");
		}
		sb.append("\r\n");
		for (int i = 0; i < header.length; i++) {
			sb.append(StringUtils.rightPad("", widths[i], '-')).append(" ");
		}
		sb.append("\r\n");
		while (itr.hasNext()) {
			final String[] row = itr.next();
			for (int i = 0; i < widths.length; i++)
				sb.append(StringUtils.rightPad(row[i], widths[i], ' ')).append(
						" ");
			sb.append("\r\n");
		}
		return sb.toString();
	}

}
